﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ARR.Entities;
using Telerik.Windows.Controls;
using ARR.UI.ViewModels;
using Telerik.Windows.Controls.GridView;
using ARR.UI.Helpers;
using System.Windows.Markup;
using System.IO;
using System.Xml;
using OfficeOpenXml;
using System.Collections.ObjectModel;

namespace ARR.UI.Views
{
    /// <summary>
    /// Interaction logic for ArticlesView.xaml
    /// </summary>
    public partial class ArticleMasterView : UserControl
    {
        public ArticleMasterView()
        {
            InitializeComponent();
            this.ArticlesGV.PreparingCellForEdit += new EventHandler<GridViewPreparingCellForEditEventArgs>(ArticlesGV_PreparingCellForEdit);
        }

        void ArticlesGV_PreparingCellForEdit(object sender, GridViewPreparingCellForEditEventArgs e)
        {
            if (e.Column.UniqueName == "Category")
            {
                ArticleMasterViewModel model = this.DataContext as ArticleMasterViewModel;
                currentRadDropDownButton = e.EditingElement as RadDropDownButton;
                RadTreeView treeview = currentRadDropDownButton.DropDownContent as RadTreeView;
                if (treeview != null)
                {
                    treeview.ItemsSource = model.Categories;
                    currentItem = e.Row.DataContext;
                }
            }
            if (e.Column.UniqueName == "AttributeColumn")
            {
                RadComboBox combo = e.EditingElement as RadComboBox;
                Article article = e.Row.DataContext as Article;
                ArticleMasterViewModel vm = this.DataContext as ArticleMasterViewModel;
                if (combo != null && combo.Items != null && combo.Items.Count > 0)
                {
                    AttributeType type = vm.AttributeTypes.SingleOrDefault(x => x.Id == ((Entities.Attribute)combo.Items[0]).AttributeTypeId);

                    if (article != null && type != null)
                    {
                        combo.ItemsSource = type.Values.Where(x => !x.CategoryId.HasValue ||
                            (x.CategoryId == article.CategoryId || (article.Category != null && x.CategoryId == article.Category.ParentId)));

                        combo.SelectionChanged -= new SelectionChangedEventHandler(combo_SelectionChanged);
                        combo.Tag = new KeyValuePair<Article, AttributeType>(article, type);
                        var att = article.Attributes.Where(x => x.AttributeTypeId == type.Id).FirstOrDefault();
                        if (att != null)
                        {
                            combo.SelectedValue = att.Id;
                        }
                        combo.SelectionChanged += new SelectionChangedEventHandler(combo_SelectionChanged);
                    }
                }
            }
        }

        void combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyValuePair<Article, AttributeType> keys = (KeyValuePair<Article, AttributeType>)((RadComboBox)sender).Tag;
            var att = keys.Key.Attributes.Where(x => x.AttributeTypeId == keys.Value.Id).FirstOrDefault();

            //Primero veo si tiene un atributo existente para este tipo y lo saco
            if (att != null)
            {
                keys.Key.Attributes.Remove(att);
            }

            //Despues lo agrego
            if (e.AddedItems.Count > 0)
            {
                keys.Key.Attributes.Add(e.AddedItems[0] as ARR.Entities.Attribute);
            }
        }

        private object currentItem;
        private RadDropDownButton currentRadDropDownButton;
        private void RadTreeView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RadTreeView treeview = sender as RadTreeView;
            if (treeview != null && treeview.SelectedItem != null)
            {
                if (((Entities.Category)treeview.SelectedItem).Level == 2)
                {
                    MessageBox.Show("Los SKUs sólo pueden ser asociados a una subcategoría");
                }
                else
                {
                    if (currentItem != null)
                    {
                        ((Article)currentItem).Category = treeview.SelectedItem as Category;
                        ((Article)currentItem).CategoryId = ((Category)treeview.SelectedItem).Id;
                        if (currentRadDropDownButton != null)
                        {
                            currentRadDropDownButton.IsOpen = false;
                            this.ArticlesGV.CommitEdit();
                        }
                    }
                }
            }
        }

        private void HeaderCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            string column = ((CheckBox)sender).Name;
            foreach (var item in this.ArticlesGV.Items)
            {
                Article article = item as Article;
                switch (column)
                {
                    case "Delist":
                        article.Delist = true;
                        break;
                    case "DeleteRR":
                        article.IsDeletedRangeReview = true;
                        break;
                    case "DeletePerf":
                        article.IsDeletedPerformance = true;
                        break;
                    case "Select":
                        article.IsSelected = true;
                        break;
                    case "IsDelisted":
                        article.IsDelisted = true;
                        article.IsDeletedRangeReview = true;
                        break;
                    case "IsNew":
                        article.IsNew = true;
                        article.IsDeletedRangeReview = true;
                        break;


                }
            }

            this.ArticlesGV.Rebind();
        }

        private void HeaderCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            string column = ((CheckBox)sender).Name;
            foreach (var item in this.ArticlesGV.Items)
            {
                Article article = item as Article;
                switch (column)
                {
                    case "Delist":
                        article.Delist = false;
                        break;
                    case "DeleteRR":
                        article.IsDeletedRangeReview = false;
                        break;
                    case "DeletePerf":
                        article.IsDeletedPerformance = false;
                        break;
                    case "Select":
                        article.IsSelected = false;
                        break;
                    case "IsDelisted":
                        article.IsDelisted = false;
                        article.IsDeletedRangeReview = false;
                        break;
                    case "IsNew":
                        article.IsNew = false;
                        article.IsDeletedRangeReview = false;
                        break;
                }
            }

            this.ArticlesGV.Rebind();
        }

        private void JoinButton_Click(object sender, RoutedEventArgs e)
        {
            List<Article> articles = new List<Article>();
            foreach (var item in this.ArticlesGV.Items)
            {
                Article article = item as Article;
                if (article.IsSelected)
                {
                    articles.Add(article);
                }
            }

            if (articles.Count != 2)
            {
                (new Alert("Debe seleccionar 2 artículos para realizar esta operación.", "Unir artículos", AlertType.Warning)).ShowDialog();
            }
            else
            {
                ArticleMasterJoinPopupView popup = new ArticleMasterJoinPopupView(articles);
                bool? dialog = popup.ShowDialog();
                if (dialog.HasValue && dialog.Value) //Si se ejecuto la opcion Unir vuelvo a traer de la base todos los Articulos
                {
                    ArticleMasterViewModel vm = this.DataContext as ArticleMasterViewModel;
                    if (vm != null)
                    {
                        vm.FilterByCategory();
                    }
                }
            }
        }

        private void ExportButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();
            dialog.DefaultExt = ".xlsx";
            dialog.Filter = "Excel File (.xlsx)|*.xlsx";
            if (dialog.ShowDialog() == true)
            {
                using (ExcelPackage p = new ExcelPackage())
                {
                    SetWorkbookProperties(p);

                    //Create a sheet
                    p.Workbook.Worksheets.Add("Article Master");
                    ExcelWorksheet ws = p.Workbook.Worksheets[1];
                    ws.Name = "Article Master"; //Setting Sheet's name
                    ws.Cells.Style.Font.Size = 11; //Default font size for whole sheet
                    ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet

                    #region Values

                    System.Drawing.Color Red = System.Drawing.Color.FromArgb(218, 150, 148);
                    System.Drawing.Color Green = System.Drawing.Color.FromArgb(196, 215, 155);
                    System.Drawing.Color Gray = System.Drawing.Color.FromArgb(204, 204, 204);
                    System.Drawing.Color Yellow = System.Drawing.Color.FromArgb(255, 255, 70);
                    System.Drawing.Color GrayLine = System.Drawing.Color.FromArgb(217, 217, 217);
                    System.Drawing.Color BlueLine = System.Drawing.Color.FromArgb(167, 191, 222);
                    System.Drawing.Color BlueText = System.Drawing.Color.FromArgb(31, 73, 125);
                    System.Drawing.Color BlueTotalTableHeader = System.Drawing.Color.FromArgb(79, 129, 189);
                    System.Drawing.Color CategoryComparisonYellow = System.Drawing.Color.FromArgb(255, 255, 153);
                    System.Drawing.Color CategoryComparisonGray = System.Drawing.Color.FromArgb(216, 216, 216);

                    string FormatCurrencyTwoDecimals = "_ $ * #.##0,00_ ;_ $ * -#.##0,00_ ;_ $ * \" - \"??_ ;_ @_ ";
                    string FormatPercentageOneDecimal = @"0.0%";
                    string FormatMetersTwoDecimal = @"0.00 ""mt.""";
                    string FormatTwoDecimals = @"0.00";
                    string FormatNoDecimals = @"0";

                    #endregion

                    #region Data

                    int headRow = 2;

                    //Completo el Header
                    ws.Cells[headRow, 1].Value = "Article";
                    ws.Cells[headRow, 2].Value = "Article EAN";
                    ws.Cells[headRow, 3].Value = "Subcategory Code";
                    ws.Cells[headRow, 4].Value = "Article Name";
                    ws.Cells[headRow, 5].Value = "Manufact";
                    ws.Cells[headRow, 6].Value = "SP w VAT (";
                    ws.Cells[headRow, 7].Value = "UOM";
                    ws.Cells[headRow, 8].Value = "Type";
                    ws.Cells[headRow, 9].Value = "Site";
                    ws.Cells[headRow, 10].Value = "Ord";
                    ws.Cells[headRow, 11].Value = "EAN (Order)";
                    ws.Cells[headRow, 12].Value = "VC";
                    ws.Cells[headRow, 13].Value = "T";
                    ws.Cells[headRow, 14].Value = "Pack";
                    ws.Cells[headRow, 15].Value = "F";
                    ws.Cells[headRow, 16].Value = "Vendor";
                    ws.Cells[headRow, 17].Value = "Vendor.art.n";
                    ws.Cells[headRow, 18].Value = "PP w/o VA";
                    ws.Cells[headRow, 19].Value = "Per";
                    ws.Cells[headRow, 20].Value = "OUn";
                    ws.Cells[headRow, 21].Value = "PP w/o VAT";
                    ws.Cells[headRow, 22].Value = "Cur";
                    ws.Cells[headRow, 23].Value = "Net SP";
                    ws.Cells[headRow, 24].Value = "Tax Rate";
                    ws.Cells[headRow, 25].Value = "SPrUn";
                    ws.Cells[headRow, 26].Value = "Pricing Site Group";
                    ws.Cells[headRow, 27].Value = "PL";
                    ws.Cells[headRow, 28].Value = "Safe.s";
                    ws.Cells[headRow, 29].Value = "RPt";
                    ws.Cells[headRow, 30].Value = "RP.prf";
                    ws.Cells[headRow, 31].Value = "Reor.p";
                    ws.Cells[headRow, 32].Value = "Max.st";
                    ws.Cells[headRow, 33].Value = "PBC";
                    ws.Cells[headRow, 34].Value = "Pricing ref. artl";
                    ws.Cells[headRow, 35].Value = "KP";
                    ws.Cells[headRow, 36].Value = "Brand";
                    ws.Cells[headRow, 37].Value = "Created Date";
                    ws.Cells[headRow, 38].Value = "Size";
                    ws.Cells[headRow, 39].Value = "Attribute1";
                    ws.Cells[headRow, 40].Value = "Attribute2";
                    ws.Cells[headRow, 41].Value = "Attribute3";
                    ws.Cells[headRow, 42].Value = "Attribute4";
                    ws.Cells[headRow, 43].Value = "Attribute5";
                    ws.Cells[headRow, 44].Value = "Ranking";
                    ws.Cells[headRow, 45].Value = "Unidades";
                    ws.Cells[headRow, 46].Value = "Ventas";
                    ws.Cells[headRow, 47].Value = "Margen";
                    ws.Cells[headRow, 48].Value = "Margen %";
                    ws.Cells[headRow, 49].Value = "Margen % RR Ant.";
                    ws.Cells[headRow, 50].Value = "Margen % Teórico";
                    ws.Cells[headRow, 51].Value = "Acum. Ventas";
                    ws.Cells[headRow, 52].Value = "Acum. SKUs";
                    ws.Cells[headRow, 53].Value = "Cobertura";
                    ws.Cells[headRow, 54].Value = "Cobertura Tiendas";
                    ws.Cells[headRow, 55].Value = "Cobertura Tiendas %";
                    ws.Cells[headRow, 56].Value = "Cobertura Meses";
                    ws.Cells[headRow, 57].Value = "Cobertura Meses %";
                    ws.Cells[headRow, 58].Value = "Unidades Norm.";
                    ws.Cells[headRow, 59].Value = "Ventas Norm.";
                    ws.Cells[headRow, 60].Value = "Share Ventas %";
                    ws.Cells[headRow, 61].Value = "Share Espacios %";
                    ws.Cells[headRow, 62].Value = "Gap Ventas/Espacios";
                    ws.Cells[headRow, 63].Value = "Status";
                    ws.Cells[headRow, 64].Value = "Categoría";
                    ws.Cells[headRow, 65].Value = "SubCategoría";
                    ws.Cells[headRow, 66].Value = "Inventario";

                    //Espacios
                    ws.Cells[headRow, 67].Value = "Width";
                    ws.Cells[headRow, 68].Value = "Facings";
                    ws.Cells[headRow, 69].Value = "Linear Space Mts";
                    ws.Cells[headRow, 70].Value = "Planograms";

                    //IMPORTANTE: Mantener este numero actualizado para generar correctamente las columnas dinamicas.
                    int lastFixedColum = 71;
                    ArticleMasterViewModel vm = this.DataContext as ArticleMasterViewModel;
                    int columnCount = lastFixedColum;
                    foreach (var location in vm.PlanogramLocations)
                    {
                        ws.Cells[2, columnCount++].Value = location.Name;
                    }

                    foreach (AttributeType type in vm.AttributeTypes.OrderBy(x => x.Id))
                    {
                        ws.Cells[2, columnCount++].Value = type.Name;
                    }

                    //Completo los datos
                    int row = 3;
                    //foreach (var article in (ObservableCollection<Article>)this.ArticlesGV.ItemsSource)
                    foreach (Article article in this.ArticlesGV.Items)
                    {
                        if (!article.IsDeletedPerformance)
                        {
                            ws.Cells[row, 1].Value = article.Code;
                            //ws.Cells[row, 1].Style.Numberformat.Format = "@";
                            ws.Cells[row, 2].Value = article.EAN;
                            //ws.Cells[row, 2].Style.Numberformat.Format = "@";
                            ws.Cells[row, 3].Value = article.Category.Code;
                            //ws.Cells[row, 3].Style.Numberformat.Format = "@";
                            ws.Cells[row, 4].Value = article.Name;
                            ws.Cells[row, 5].Value = article.Manufacturer;
                            ws.Cells[row, 6].Value = article.Price;
                            ws.Cells[row, 7].Value = article.UOM;
                            ws.Cells[row, 8].Value = article.Type;
                            ws.Cells[row, 10].Value = article.OrderUOM;
                            ws.Cells[row, 11].Value = article.OrderEAN;
                            ws.Cells[row, 14].Value = article.Pack;
                            ws.Cells[row, 16].Value = article.Vendor;
                            ws.Cells[row, 24].Value = article.TaxRate;
                            ws.Cells[row, 36].Value = article.Brand;
                            ws.Cells[row, 37].Style.Numberformat.Format = "dd/MM/yyyy";
                            if (article.CreatedDate.HasValue)
                                ws.Cells[row, 37].Value = article.CreatedDate.Value.ToString("dd/MM/yyyy");
                            else
                                ws.Cells[row, 37].Value = null;

                            ws.Cells[row, 38].Value = article.Size;
                            ws.Cells[row, 39].Value = article.Attribute1;
                            ws.Cells[row, 40].Value = article.Attribute2;
                            ws.Cells[row, 41].Value = article.Attribute3;
                            ws.Cells[row, 42].Value = article.Attribute4;
                            ws.Cells[row, 43].Value = article.Attribute5;

                            //A partir de aca empieza info de ventas
                            ws.Cells[row, 44].Value = article.Ranking;
                            ws.Cells[row, 45].Value = article.Units;
                            ws.Cells[row, 46].Value = article.Sales;
                            ws.Cells[row, 47].Value = article.Margin;
                            ws.Cells[row, 48].Value = article.MarginP;
                            ws.Cells[row, 50].Value = article.TheoreticalMargin;
                            ws.Cells[row, 51].Value = article.AcumSales;
                            ws.Cells[row, 52].Value = article.AcumSKUs;
                            ws.Cells[row, 53].Value = article.Coverage;
                            ws.Cells[row, 54].Value = article.StoreCoverageQuantity;
                            ws.Cells[row, 55].Value = article.StoreCoverage;
                            ws.Cells[row, 56].Value = article.MonthsCoverageQuantity;
                            ws.Cells[row, 57].Value = article.MonthsCoverage;
                            ws.Cells[row, 58].Value = article.NormalizeUnits;
                            ws.Cells[row, 59].Value = article.NormalizeSales;
                            ws.Cells[row, 60].Value = article.SalesShare;
                            ws.Cells[row, 61].Value = article.SpaceShare;
                            ws.Cells[row, 62].Value = article.GapSalesSpace;

                            ws.Cells[row, 63].Value = article.Status;
                            ws.Cells[row, 64].Value = vm.Categories.Where(x => x.Id == article.Category.ParentId).FirstOrDefault().Name;
                            ws.Cells[row, 65].Value = article.Category.Name;
                            ws.Cells[row, 66].Value = article.InventoryCost;

                            //Espacios
                            ws.Cells[row, 67].Value = article.Width;
                            ws.Cells[row, 68].Value = article.Facings;
                            ws.Cells[row, 69].Value = article.LinearSpaceMts;
                            ws.Cells[row, 70].Value = article.Planograms;

                            columnCount = lastFixedColum;

                            foreach (var location in vm.PlanogramLocations)
                            {
                                if (article.SpacesByLocation != null)
                                {
                                    string value = string.Empty;
                                    article.SpacesByLocation.TryGetValue(location.Name, out value);
                                    decimal decimalValue = 0;
                                    if (decimal.TryParse(value, out decimalValue))
                                    {
                                        ws.Cells[row, columnCount++].Value = decimalValue;
                                    }
                                    else
                                    {
                                        ws.Cells[row, columnCount++].Value = value;
                                    }
                                }
                                else
                                {
                                    ws.Cells[row, columnCount++].Value = null;
                                }
                            }

                            //Despues de la info de ventas va la segmentación Dinámica
                            foreach (AttributeType type in vm.AttributeTypes.OrderBy(x => x.Id))
                            {
                                Entities.Attribute value = article.Attributes.SingleOrDefault(x => x.AttributeTypeId == type.Id);
                                ws.Cells[row, columnCount++].Value = value != null ? value.AttributeValue : null;
                            }


                            //Pinto la fila segun las ventas acumuladas
                            if (article.PrevAcumSales <= 0.8m)
                            {
                                ExcelHelper.SetStyles(ws.Cells[row, 1, row, columnCount - 1], OfficeOpenXml.Style.ExcelBorderStyle.Thin, Green);                                    
                            }
                            else if (article.AcumSales > 0.95m)
                            {
                                ExcelHelper.SetStyles(ws.Cells[row, 1, row, columnCount - 1], OfficeOpenXml.Style.ExcelBorderStyle.Thin, Red);                                    
                            }

                            if (article.IsDeletedRangeReview)
                            {
                                ExcelHelper.SetStyles(ws.Cells[row, 1, row, columnCount - 1], OfficeOpenXml.Style.ExcelBorderStyle.Thin, Gray);                                    
                            }

                            row++;
                        }
                    }
                    #endregion

                    #region Styles

                    columnCount--;
                    row--;

                    //Sheet Styles
                    ws.View.FreezePanes(3, 5);
                    ws.View.ShowGridLines = false;
                    ws.View.ZoomScale = 80;
                    ws.Cells.Style.Font.Size = 11; //Default font size for whole sheet
                    ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet

                    //Column Widths
                    ws.defaultColWidth = 15;
                    ws.Column(4).Width = 50;

                    //Whole Table Styles
                    ExcelHelper.SetBorders(ws.Cells[headRow, 1, row, columnCount], OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    
                    //Header Styles
                    ws.Cells[headRow, 1, headRow, columnCount].Style.WrapText = true;
                    ws.Cells[headRow, 1, headRow, columnCount].Style.Font.Bold = true;
                    ws.Cells[headRow, 1, headRow, columnCount].Style.Font.Color.SetColor(System.Drawing.Color.White);
                    ws.Cells[headRow, 1, headRow, columnCount].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                    ws.Cells[headRow, 1, headRow, columnCount].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    ExcelHelper.SetStyles(ws.Cells[headRow, 1, headRow, columnCount], OfficeOpenXml.Style.ExcelBorderStyle.Thin, BlueTotalTableHeader);

                    //Number Formats
                    ws.Cells[headRow + 1, 6, row, 6].Style.Numberformat.Format = FormatCurrencyTwoDecimals;     //Price
                    ws.Cells[headRow + 1, 24, row, 24].Style.Numberformat.Format = FormatPercentageOneDecimal;  //TaxRate
                    ws.Cells[headRow + 1, 38, row, 38].Style.Numberformat.Format = FormatTwoDecimals;           //Size
                    ws.Cells[headRow + 1, 45, row, 45].Style.Numberformat.Format = FormatNoDecimals;            //Units
                    ws.Cells[headRow + 1, 46, row, 46].Style.Numberformat.Format = FormatCurrencyTwoDecimals;   //Sales
                    ws.Cells[headRow + 1, 47, row, 47].Style.Numberformat.Format = FormatCurrencyTwoDecimals;   //Margin
                    ws.Cells[headRow + 1, 48, row, 48].Style.Numberformat.Format = FormatPercentageOneDecimal;  //MarginP
                    ws.Cells[headRow + 1, 49, row, 49].Style.Numberformat.Format = FormatPercentageOneDecimal;   //MarginP RR Ant %
                    ws.Cells[headRow + 1, 50, row, 50].Style.Numberformat.Format = FormatPercentageOneDecimal;   //Margin Teorico %
                    ws.Cells[headRow + 1, 51, row, 51].Style.Numberformat.Format = FormatPercentageOneDecimal;   //Acum Sales
                    ws.Cells[headRow + 1, 52, row, 52].Style.Numberformat.Format = FormatPercentageOneDecimal;   //Acum SKus
                    ws.Cells[headRow + 1, 53, row, 53].Style.Numberformat.Format = FormatPercentageOneDecimal;   //Coverage
                    ws.Cells[headRow + 1, 55, row, 55].Style.Numberformat.Format = FormatPercentageOneDecimal;   //%
                    ws.Cells[headRow + 1, 57, row, 57].Style.Numberformat.Format = FormatPercentageOneDecimal;   //%
                    ws.Cells[headRow + 1, 58, row, 58].Style.Numberformat.Format = FormatNoDecimals;   //Unidades Norm
                    ws.Cells[headRow + 1, 59, row, 59].Style.Numberformat.Format = FormatCurrencyTwoDecimals;   //Ventas Norm
                    ws.Cells[headRow + 1, 60, row, 60].Style.Numberformat.Format = FormatPercentageOneDecimal;   //Share Ventas
                    ws.Cells[headRow + 1, 61, row, 61].Style.Numberformat.Format = FormatPercentageOneDecimal;   //Share Space
                    ws.Cells[headRow + 1, 62, row, 62].Style.Numberformat.Format = FormatPercentageOneDecimal;   //Space/Ventas
                    ws.Cells[headRow + 1, 66, row, 66].Style.Numberformat.Format = FormatCurrencyTwoDecimals;   //Inventarios
                    ws.Cells[headRow + 1, 69, row, 69].Style.Numberformat.Format = FormatMetersTwoDecimal;   //Linear Meters

                    #endregion

                    //Generate the xslx
                    File.WriteAllBytes(dialog.FileName, p.GetAsByteArray());


                }
            }
        }

        private static void SetWorkbookProperties(ExcelPackage p)
        {
            //Here setting some document properties
            p.Workbook.Properties.Author = "Tryada";
            p.Workbook.Properties.Title = "ARR";
        }

        private void ArticlesGV_ElementExported(object sender, GridViewElementExportedEventArgs e)
        {

        }

        private void ArticlesGV_ElementExporting(object sender, GridViewElementExportingEventArgs e)
        {
            if (e.Context is GridViewDataColumn)
            {
                GridViewDataColumn column = e.Context as GridViewDataColumn;
                if (column.Tag == null)
                {
                    e.Cancel = true;
                }
                else
                {
                    if (e.Element == ExportElement.HeaderCell)
                    {
                        e.FontWeight = FontWeights.Bold;
                        e.Background = Colors.LightGray;

                        //if (column.Tag.ToString().StartsWith("Attribute"))
                        //{
                        //    e.Value = column.Tag.ToString().Split('|').ElementAt(1);
                        //    e.Width = 120;
                        //}
                        //else
                        //{
                        //    e.Value = column.Tag.ToString();
                        //}
                    }
                    else
                    {

                        if (column.Tag.ToString().StartsWith("Attribute"))
                        {
                            //Entities.Attribute attribute = ((Article)e.Value).Attributes.Where(x => x.AttributeTypeId == int.Parse(column.Tag.ToString().Split('|').ElementAt(2))).FirstOrDefault();
                            //if (attribute != null)
                            //{
                            //    e.Value = attribute.AttributeValue;
                            //}
                            //else
                            //{
                            //    e.Value = null;
                            //}
                        }
                        else
                        {
                            if (e.Value is Category)
                            {
                                e.Value = ((Category)e.Value).Name;
                            }
                        }
                    }
                }
            }

            if (e.Element == ExportElement.Row)
            {
                if (e.Value is Article)
                {
                    Article item = e.Value as Article;
                    if (item.AcumSales <= 0.8m || item.PrevAcumSales < 0.8m)
                    {
                        e.Background = Color.FromArgb(255, 196, 215, 155);
                    }
                    else if (item.AcumSales >= 0.95m)
                    {
                        e.Background = Color.FromArgb(255, 218, 150, 148);
                    }
                }
            }
        }

        private void SplitButton_Click(object sender, RoutedEventArgs e)
        {
            List<Article> articles = new List<Article>();
            foreach (var item in this.ArticlesGV.Items)
            {
                Article article = item as Article;
                if (article.IsSelected)
                {
                    articles.Add(article);
                }
            }

            if (articles.Count > 1)
            {
                (new Alert("Debe seleccionar un unico articulo para realizar esta operación.", "Desdoblar articulo", AlertType.Warning)).ShowDialog();
            }
            else if (articles.Count == 0)
            {
                (new Alert("Debe seleccionar un articulo para realizar esta operación.", "Desdoblar articulo", AlertType.Warning)).ShowDialog();
            }
            else
            {
                var viewModel = (this.DataContext as ArticleMasterViewModel);
                ArticleMasterSplitPopupViewModel vm = new ArticleMasterSplitPopupViewModel(viewModel.model, articles.First());
                ArticleMasterSplitPopupView splitPopup = new ArticleMasterSplitPopupView(vm);

                bool? result = splitPopup.ShowDialog();

                if (result.HasValue && result == true)
                {
                    viewModel.FilterByCategory();
                    new Alert("El artículo seleccionado ha sido desdoblado correctamente.", "Desdoblar Articulo", AlertType.Information);
                }
            }

        }

        private void DelistButton_Click(object sender, RoutedEventArgs e)
        {
            ArticleMasterViewModel vm = this.DataContext as ArticleMasterViewModel;
            decimal _delistBottomSalesPercentage = 0;
            decimal _delistBottomUnitsPercentage = 0;
            decimal _delistBottomMarginPercentage = 0;
            decimal _delistMaxCoveragePercentage = 0;
            if (!string.IsNullOrEmpty(DelistBottomSalesPercentage.Text) && DelistBottomSalesPercentage.Text != "0")
            {
                _delistBottomSalesPercentage = decimal.Parse(DelistBottomSalesPercentage.Text) / 100m;
            }
            if (!string.IsNullOrEmpty(DelistBottomUnitsPercentage.Text) && DelistBottomUnitsPercentage.Text != "0")
            {
                _delistBottomUnitsPercentage = decimal.Parse(DelistBottomUnitsPercentage.Text) / 100m;
            }
            if (!string.IsNullOrEmpty(DelistBottomMarginPercentage.Text) && DelistBottomMarginPercentage.Text != "0")
            {
                _delistBottomMarginPercentage = decimal.Parse(DelistBottomMarginPercentage.Text) / 100m;
            }
            if (!string.IsNullOrEmpty(DelistMaxCoveragePercentage.Text) && DelistMaxCoveragePercentage.Text != "0")
            {
                _delistMaxCoveragePercentage = decimal.Parse(DelistMaxCoveragePercentage.Text) / 100m;
            }

            //Calculo AcumUnits
            decimal acumUnits = 0;
            decimal totalUnits = vm.Articles.Sum(x => x.Units);
            foreach (Article article in vm.Articles.OrderByDescending(x => x.Units))
            {
                acumUnits += article.Units;
                article.AcumUnits = acumUnits / totalUnits;
            }

            //Calculo AcumMargin
            decimal acumMargin = 0;
            decimal totalMargin = vm.Articles.Sum(x => x.Margin);
            foreach (Article article in vm.Articles.OrderByDescending(x => x.Margin))
            {
                acumMargin += article.Margin;
                article.AcumMargin = acumMargin / totalMargin;
            }

            foreach (var article in vm.Articles.Where(x => !x.IsDeletedRangeReview))
            {
                if ((_delistBottomSalesPercentage == 0 || (_delistBottomSalesPercentage > 0 && article.AcumSales > 0 && article.AcumSales >= (1 - _delistBottomSalesPercentage)))
                    && ((_delistBottomUnitsPercentage == 0 || (_delistBottomUnitsPercentage > 0 && article.AcumUnits > 0 && article.AcumUnits >= (1 - _delistBottomUnitsPercentage))))
                    && ((_delistBottomMarginPercentage == 0 || (_delistBottomMarginPercentage > 0 && article.AcumMargin > 0 && article.AcumMargin >= (1 - _delistBottomMarginPercentage))))
                    && (_delistMaxCoveragePercentage == 0 || (_delistMaxCoveragePercentage > 0 && article.Coverage > 0 && article.Coverage >= _delistMaxCoveragePercentage)))
                {
                    article.Delist = true;
                }
                else
                {
                    article.Delist = false;
                }
            }

            this.ArticlesGV.Rebind();
        }

    }
}
